import {computed, ref} from "vue";
import {defineStore} from 'pinia';
import {getInvasiveSpeciesDirectoryAPI} from "../../api/allAPI";
import {directoryItem} from "../../api/req";
import {message} from "ant-design-vue";

export const useDirectoryStore = defineStore('DirectoryStore', () => {
    const directorySets = ref<directoryItem[]>([]);
    const loading = ref<boolean>(false);
    const directoryPage = ref({
        currentPage: 1,
        total: 0,
        pageSize: 10,
        showSizePicker: true,
        pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
    });

    const updateDirectorySets = async (term?: string) => {
        loading.value = true;
        const req = {
            pageNo: directoryPage.value.currentPage,
            pageSize: directoryPage.value.pageSize,
            searchTerm: term || undefined,
        };
        if (term) {
            req.pageNo = 1;
        }
        const res = await getInvasiveSpeciesDirectoryAPI(req);
        const { data, meta } = res.data;
        directorySets.value = data.map((item: any) => ({
            number: item.id,
            name: item.attributes.ScientificName,
            cname: item.attributes.ChineseName,
            links: [item.attributes.link],
            data: item.attributes.Time,
            country: item.attributes.Area,
            status: item.attributes.Type,
        }));
        directoryPage.value.total = meta.pagination.total
        if (term) {
            if (meta.pagination.total === 0) {
                message.warning({
                    content: '暂无数据',
                    duration: 3,
                    class: 'custom-message'
                });
            } else {
                message.success({
                    content: `搜索成功，共 ${meta.pagination.total} 条数据`,
                    duration: 1,
                    class: 'custom-message'
                });
            }
        }
        loading.value = false;
    };

    // 设置分页信息
    const setDirectorySetsPage = (page?: number) => {
        if (page) directoryPage.value.currentPage = page;
    };

    const getDirectorySets = computed(() => {
        return directorySets.value;
    });

    const getDirectoryPage = computed(() => {
        return directoryPage.value;
    });

    const pagination = computed(() => ({
        current: directoryPage.value.currentPage,
        total: directoryPage.value.total,
        pageSize: directoryPage.value.pageSize,
        onChange: (page: number) => {
            setDirectorySetsPage(page);
            updateDirectorySets().then()
        },
    }));

    const getPlantLoading = computed(() => {
        return loading.value;
    });

    return {
        updateDirectorySets,
        setDirectorySetsPage,
        getDirectorySets,
        getDirectoryPage,
        pagination,
        getPlantLoading
    }
})